package com.guzhi.controller;

import com.guzhi.pojo.Result;
import com.guzhi.utils.AliyunOSSOperator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.UUID;

@RequestMapping("/upload")
@RestController
public class UploadController {
    private static final Logger log = LoggerFactory.getLogger(EmpController.class);
    @Autowired
    private AliyunOSSOperator aliyunOSSOperator;

//基于本地存储
//    @PostMapping
//    public Result upload(String name, Integer age, MultipartFile file) throws Exception {
//        log.info("接收参数为：{},{},{}", name, age, file);
//
//        //获取原始文件名
//        String originalFilename = file.getOriginalFilename();
//        //新的文件名（防止文件名一样，导致出现问题，通过UUID随机生成字符串）
//        String extension = originalFilename.substring(originalFilename.lastIndexOf("."));
//        String newFileName = UUID.randomUUID().toString() + extension;
//        //保存文件
//        file.transferTo(new File("D:/image/" + newFileName));
//
//
//        return Result.success();
//    }

    //基于阿里云存储
    @PostMapping
    public Result upload(MultipartFile file) throws Exception {
        log.info("文件上传：{}", file);
        String url = aliyunOSSOperator.upload(file.getBytes(), file.getOriginalFilename());
        log.info("文件上传成功，返回访问url：{}", url);
        return Result.success(url);
    }
}
